import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
// import qs from 'qs'
import nprogress from 'nprogress'
import 'nprogress/nprogress.css'

// create an axios instance
const service = axios.create({
  baseURL: process.env.BASE_API, // api的base_url
  timeout: 5000 // request timeout
})

service.defaults.headers.get['X-Requested-With'] = 'XMLHttpRequest'
service.defaults.headers.post['X-Requested-With'] = 'XMLHttpRequest'
service.defaults.headers.patch['X-Requested-With'] = 'XMLHttpRequest'
service.defaults.headers.delete['X-Requested-With'] = 'XMLHttpRequest'

// 多余封装
// service.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'
// service.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8'
// service.defaults.responseType = 'json'
// service.defaults.transformRequest = [function(data) {
// 数据序列化
// return qs.stringify(data)
// return data
// return JSON.stringify(data)
// }
// ]

// request interceptor
service.interceptors.request.use(config => {
  nprogress.start()
  // Do something before request is sent
  if (store.getters.token) {
    config.headers['X-Token'] = getToken() // 让每个请求携带token-- ['X-Token']为自定义key 请根据实际情况自行修改
  }
  return config
}, error => {
  // Do something with request error
  console.log(error) // for debug
  Promise.reject(error)
})

// respone interceptor
service.interceptors.response.use(
  response => {
    nprogress.done()
    checkStatus(response)
    return response
  },
  error => {
    nprogress.done()
    checkStatus(error.response)
    // 统一扶正错误状态 30X,40X,50X等异常，后续不需要再写catch
    return Promise.resolve(error.response)
  })

// 统一判断返回状态值
function checkStatus(response) {
  // 200是正常返回，否则例如206表明业务逻辑不正确
  if (!response) {
    Message({
      message: '服务器请求超时',
      type: 'error',
      dangerouslyUseHTMLString: true,
      duration: 5 * 1000
    })
    Promise.reject('请求超时')
    return
  }
  if (response.status === 200) {
    return response
  }
  if (response.status === 206 || response.status === 500 || response.status === 422) {
    const errorMessage = response.data.errorText + '<br/><br/>' + '错误码: ' + response.data.errorCode
    if (response.data.messageDebug) {
      console.error('服务端调试信息:' + JSON.stringify(response.data.messageDebug))
    }
    Message({
      message: errorMessage,
      showClose: true,
      type: 'error',
      dangerouslyUseHTMLString: true,
      duration: 5 * 1000
    })
    return response
  }
  if (response.status === 401) {
    Message({
      message: '登录已过期',
      showClose: true,
      type: 'error',
      center: true,
      duration: 5 * 1000
    })
    store.dispatch('FedLogOut').then(() => {
      location.reload()
    })
    return response
  }
  if (response.status === 404) {
    Message({
      message: '无效请求',
      showClose: true,
      type: 'error',
      center: true,
      duration: 5 * 1000
    })
    return response
  }
  return response
}

export default service
